/*
 * Copyright (c) Thorben Linneweber and others
 *
 * Permission is hereby granted, free of charge, to any person obtaining
 * a copy of this software and associated documentation files (the
 * "Software"), to deal in the Software without restriction, including
 * without limitation the rights to use, copy, modify, merge, publish,
 * distribute, sublicense, and/or sell copies of the Software, and to
 * permit persons to whom the Software is furnished to do so, subject to
 * the following conditions:
 *
 * The above copyright notice and this permission notice shall be
 * included in all copies or substantial portions of the Software.
 *
 * THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND,
 * EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF
 * MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND
 * NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE
 * LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION
 * OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION
 * WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE.
 */

using System;
using Jitter2.LinearMath;

using SoftFloat;

namespace Jitter2.Collision.Shapes
{
	
	/// <summary>
	/// Represents a three-dimensional box shape.
	/// </summary>
	public class BoxShape : RigidBodyShape
	{
	    private NVector3 halfSize;
	
	    /// <summary>
	    /// Gets or sets the dimensions of the box.
	    /// </summary>
	    public NVector3 Size
	    {
	        get => (sfloat)2.0f * halfSize;
	        set
	        {
	            halfSize = value * (sfloat)0.5f;
	            UpdateWorldBoundingBox(sfloat.Zero);
	        }
	    }
	
	    /// <summary>
	    /// Creates a box shape with specified dimensions.
	    /// </summary>
	    /// <param name="size">The dimensions of the box.</param>
	    public BoxShape(NVector3 size)
	    {
	        halfSize = (sfloat)0.5f * size;
	        UpdateWorldBoundingBox(sfloat.Zero);
	    }
	
	    /// <summary>
	    /// Creates a cube shape with the specified side length.
	    /// </summary>
	    /// <param name="size">The length of each side of the cube.</param>
	    public BoxShape(sfloat size)
	    {
	        halfSize = new NVector3(size * (sfloat)0.5f);
	        UpdateWorldBoundingBox(sfloat.Zero);
	    }
	
	    /// <summary>
	    /// Creates a box shape with the specified length, height, and width.
	    /// </summary>
	    /// <param name="length">The length of the box.</param>
	    /// <param name="height">The height of the box.</param>
	    /// <param name="width">The width of the box.</param>
	    public BoxShape(sfloat length, sfloat height, sfloat width)
	    {
	        halfSize = (sfloat)0.5f * new NVector3(length, height, width);
	        UpdateWorldBoundingBox(sfloat.Zero);
	    }
	
	    public override void SupportMap(in NVector3 direction, out NVector3 result)
	    {
	        result.X = libm.Sign(direction.X) * halfSize.X;
	        result.Y = libm.Sign(direction.Y) * halfSize.Y;
	        result.Z = libm.Sign(direction.Z) * halfSize.Z;
	    
	        result += centerOffset;// 应用中心偏移
		}
	
	    public override bool LocalRayCast(in NVector3 origin, in NVector3 direction, out NVector3 normal, out sfloat lambda)
	    {
	        sfloat epsilon = 1e-22f;
	
	        NVector3 min = -halfSize;
	        NVector3 max = halfSize;
	
	        normal = NVector3.Zero;
	        lambda = (sfloat)0.0f;
	
	        sfloat exit = sfloat.PositiveInfinity;
	
	        if (libm.Abs(direction.X) > epsilon)
	        {
	            sfloat ix = (sfloat)1.0f / direction.X;
	            sfloat t0 = (min.X - origin.X) * ix;
	            sfloat t1 = (max.X - origin.X) * ix;
	
	            if (t0 > t1) (t0, t1) = (t1, t0);
	
	            if (t0 > exit || t1 < lambda) return false;
	
	            if (t0 > lambda)
	            {
	                lambda = t0;
	                normal = direction.X < (sfloat)0.0f ? NVector3.UnitX : -NVector3.UnitX;
	            }
	
	            if (t1 < exit) exit = t1;
	        }
	        else if (origin.X < min.X || origin.X > max.X)
	        {
	            return false;
	        }
	
	        if (libm.Abs(direction.Y) > epsilon)
	        {
	            sfloat iy = (sfloat)1.0f / direction.Y;
	            sfloat t0 = (min.Y - origin.Y) * iy;
	            sfloat t1 = (max.Y - origin.Y) * iy;
	
	            if (t0 > t1) (t0, t1) = (t1, t0);
	
	            if (t0 > exit || t1 < lambda) return false;
	
	            if (t0 > lambda)
	            {
	                lambda = t0;
	                normal = direction.Y < (sfloat)0.0f ? NVector3.UnitY : -NVector3.UnitY;
	            }
	
	            if (t1 < exit) exit = t1;
	        }
	        else if (origin.Y < min.Y || origin.Y > max.Y)
	        {
	            return false;
	        }
	
	        if (libm.Abs(direction.Z) > epsilon)
	        {
	            sfloat iz = (sfloat)1.0f / direction.Z;
	            sfloat t0 = (min.Z - origin.Z) * iz;
	            sfloat t1 = (max.Z - origin.Z) * iz;
	
	            if (t0 > t1) (t0, t1) = (t1, t0);
	
	            if (t0 > exit || t1 < lambda) return false;
	
	            if (t0 > lambda)
	            {
	                lambda = t0;
	                normal = direction.Z < (sfloat)0.0f ? NVector3.UnitZ : -NVector3.UnitZ;
	            }
	            //if (t1 < exit) exit = t1;
	        }
	        else if (origin.Z < min.Z || origin.Z > max.Z)
	        {
	            return false;
	        }
	
	        return true;
	    }
	
	    public override void GetCenter(out NVector3 point)
	    {
	        point = centerOffset;
	    }
	
	    public override void CalculateBoundingBox(in NQuaternion orientation, in NVector3 position, out JBBox box)
	    {
	        JMatrix.Absolute(JMatrix.CreateFromQuaternion(orientation), out JMatrix absm);
	        var ths = NVector3.Transform(halfSize, absm);
	        box.Min = position - ths;
	        box.Max = position + ths;
	    
	        // 考虑位置和中心偏移
	        box.Min += centerOffset;
	        box.Max += centerOffset;
		}
	
	    public override void CalculateMassInertia(out JMatrix inertia, out NVector3 com, out sfloat mass)
	    {
	        NVector3 size = halfSize * (sfloat)2.0f;
	        mass = size.X * size.Y * size.Z;
	
	        inertia = JMatrix.Identity;
	        inertia.M11 = (sfloat)1.0f / (sfloat)12.0f * mass * (size.Y * size.Y + size.Z * size.Z);
	        inertia.M22 = (sfloat)1.0f / (sfloat)12.0f * mass * (size.X * size.X + size.Z * size.Z);
	        inertia.M33 = (sfloat)1.0f / (sfloat)12.0f * mass * (size.X * size.X + size.Y * size.Y);
	
	        com = NVector3.Zero;
	    }
	}
}
